/**
 * Created by fjlongtou on 2016/11/28.
 */
var mysql = require('mysql');
var poolcache = [];
var DbPool = function () {
    this.host = "";
    this.user = "";
    this.password = "";
    this.database = "";
    this.port = "";
    this.isCreated = false;
    this.isExists = function (config) {
        if (this.isCreated && config.host == this.host && config.user == this.user && config.password == this.password && config.database == this.database && config.port == this.port)
        {
            return true;
        }
        return false;
    };
    this.createPool = function (config) {
        this.pool = mysql.createPool(config);
    };
    this.getPool = function () {
        if (!this.isCreated)
        {
            //监听connecttion
            this.pool.on('connection',function () {
                this.isCreated = true;
            });
        }
        return this.pool;
    };
}
exports.getPool = function(config){
    var pool = null;
    for(var idx = 0; idx < poolcache.length; idx++)
    {
        var tmppool = poolcache[idx];
        if (tmppool.isExists(config))
        {
            pool = tmppool.getPool();
            break;
        }
    }
    if (pool == null)
    {
        var dbPool = new DbPool();
        dbPool.createPool(config);
        poolcache.push(dbPool);
        pool = dbPool.getPool();
    }
    return pool;
};

exports.query = function(config,sql,sqlParam,callback) {
    var pool = exports.getPool(config);
    pool.getConnection(function(err,conn){
        if(err){
            callback(err,null,null);
            console.log("query err "+err.message);
        }else{
            conn.query(sql,sqlParam,function(qerr,vals,fields){
                //释放连接
                conn.release();
                //事件驱动回调
                callback(qerr,vals,fields);
            });
        }
    });
};


